package com.xj.openapi4j.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.xj.openapi4j.commons.TokenManager;
import  com.xj.openapi4j.exception.OpenAPIException;
import  com.xj.openapi4j.model.Record;
import  com.xj.openapi4j.platform.TradeService;
import com.xj.openapi4j.service.token.U8Token;
import com.xj.openapi4j.service.token.YsToken;
import  com.xj.openapi4j.util.HttpUtil;
import com.xj.openapi4j.util.RequestTool;
import com.xj.util.Constance;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CustomerService  {

	@Value("${u8AppKey}")
	String u8AppKey;

	@Value("${u8AppSecret}")
	String u8AppSecret;
	@Value("${fromAccount}")
	String from_account;

	@Autowired
	U8Token u8Token;
    @Autowired
	RedisTemplate redisTemplate;
    @Autowired
	YsToken ysToke;


	public JSONObject getCustominfo(String name,String code) throws Exception {
		Object  customerInfo=null;
		if(StringUtils.isNotEmpty(name)){
			  customerInfo=redisTemplate.opsForHash().get(Constance.customer,name);
		}
		if(customerInfo==null) {
			   String url = "https://api.yonyouup.com/api/customer/batch_get";
			   Map<String, String> paramMap = new HashMap();
			   paramMap.put("from_account", from_account);
			   paramMap.put("to_account", from_account);
			   if(StringUtils.isNotEmpty(name)){
				   paramMap.put("name", name);
			   }
			  if(StringUtils.isNotEmpty(code)){
				  paramMap.put("code_begin",code);
				  paramMap.put("code_end",code);
			  }
			   paramMap.put("app_key", u8AppKey);
			   paramMap.put("token", u8Token.getToken());
			   String str = RequestTool.doGet(url, paramMap);
			   JSONObject jsonObject = JSONObject.parseObject(str);
			   if("0".equals(jsonObject.getString("errcode"))){
				   JSONArray jsonArray=jsonObject.getJSONArray("customer");
				   JSONObject data=jsonArray.getJSONObject(0);
				   if(StringUtils.isNotEmpty(name)){
					   redisTemplate.opsForHash().put(Constance.customer, name, data);
				   }
				   return data;
			   }
		   }else {
			   return  (JSONObject) customerInfo;
		   }
            return null;
	}

	public  String  transCustomerBycode(String  code) throws Exception{
		JSONObject data=getCustominfo(null,code);
	 return 	transCustomer2YS(data);
	}


	public  String  transCustomer2YS(JSONObject  data) throws Exception{
		String ysTokeToken=ysToke.getToken();
		String url="https://c3.yonyoucloud.com/iuap-api-auth/yonbip/digitalModel/merchant/newinsert?access_token="+ysTokeToken;
         JSONObject body=new JSONObject();
		 body.put("code",data.getString("code"));
		 JSONObject name=new JSONObject();
		 name.put("simplifiedName",data.getString("name"));
		 body.put("name",name);
		 body.put("createOrgCode","001");
         body.put("transTypeCode","SYCSR001");
		 JSONObject shortname=new JSONObject();
		 shortname.put("simplifiedName",data.getString("abbrname"));
		 body.put("shortname",shortname);
		 body.put("retailInvestors",false);
		 body.put("internalOrg",false);
         body.put("taxPayingCategories",0);
		 body.put("customerClassCode","11");
		 body.put("enterpriseNature",0);
		 body.put("enterpriseName",data.getString("name"));
         body.put("licenseType",0);
		 //u8 api接口无税号字段
       //  body.put("creditCode",)
		String contact=data.getString("contact");
		String mobile=data.getString("mobile");


         body.put("email",data.getString("email"));
		 body.put("fax",data.getString("fax"));
		 body.put("contactTel",data.getString("phone"));
		 if(StringUtils.isNotEmpty(data.getString("address"))){
			 JSONArray arr=new JSONArray();
			 JSONObject merchantAddressInfos=new JSONObject();
			 merchantAddressInfos.put("addressCode","1");
			 merchantAddressInfos.put("address",data.getString("address"));
			 merchantAddressInfos.put("receiver",contact);
			 merchantAddressInfos.put("mobile",mobile);
			 merchantAddressInfos.put("stopStatus",0);
			 merchantAddressInfos.put("isDefault",true);
			 arr.add(merchantAddressInfos);
			 body.put("merchantAddressInfos",arr);
		 }
         JSONObject merchantAppliedDetail=new JSONObject();
	 	merchantAppliedDetail.put("deliveryWarehouseCode","bzp");
	 	merchantAppliedDetail.put("transactionCurrencyName","人民币");
        merchantAppliedDetail.put("signBack",0);
        merchantAppliedDetail.put("isTradeCustomers","0");
		body.put("merchantAppliedDetail",merchantAppliedDetail);

		JSONObject merchantRole=new JSONObject();
		merchantRole.put("merchantOptions",false);
		merchantRole.put("businessRole",2);
		body.put("merchantRole",merchantRole);
		JSONObject merchantsManager=new JSONObject();
		if(StringUtils.isNotEmpty(contact)&&contact.length()<5&&StringUtils.isNotEmpty(mobile)&&mobile.matches("\\d{11}")){
		    merchantsManager.put("countryCode","86");
			merchantsManager.put("mobile",mobile);
			merchantsManager.put("fullName",contact);
			body.put("merchantsManager",merchantsManager);
		}else {
			log.info("联系人和手机不能为空!");
			return  "联系人和手机不能为空"  ;
		}
		String str= HttpUtil.post(url,body.toJSONString());
        log.info(str);
        return str;
	}

	

}
